package dxc04;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class MyThread extends Thread {
    static int tikets = 0;
    static Lock lock = new ReentrantLock();

    //因为我们在demo1创建了多个线程对象，所以这个Lock锁也会创建多个对象，所以我们要用static修饰，使其共享化
    /*
     void lock 获得锁
        void unlock() 释放锁
     */
    @Override
    public void run() {
        //1.循环
        while (true) {
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            lock.lock();  // 获得锁
            //2.同步代码块
            try {
                if (tikets == 100) {
                    break;
                } else {
                    Thread.sleep(10);
                    tikets++;
                    System.out.println(Thread.currentThread().getName() + "卖出第" + tikets + "张票");

                }

            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            } finally {
                lock.unlock();

            }


        }
    }
}


